package com.qf.interceptor;



import com.alibaba.fastjson.JSONObject;
import com.qf.pojo.Sys_user;

import com.qf.vo.BaseResult;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Writer;

/**
 * Created by Chao.W on 2021/4/16 18:43
 */
public class MyInterceptor implements HandlerInterceptor {

    //    preHandle在请求到达在请求到达controller之前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        HttpSession session = request.getSession();
        Sys_user user = (Sys_user) session.getAttribute("user");
        if (user != null) {
            return true;
        }

        BaseResult baseResult = new BaseResult();
        baseResult.setCode(204);
        baseResult.setMessage("请先登录");
        //将返回baseResult转为json格式
        String string = JSONObject.toJSONString(baseResult);

        //将错误信息写到页面上
        response.setContentType("application/json");//设置在页面打印的响应的类型为json
        response.setCharacterEncoding("utf-8");//设置在页面打印的响应的编码为utf-8
        Writer writer = response.getWriter();
        writer.write(string);
        return false;
    }
}
